<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 17:58:55
 * @email: ligui0506@sina.com
 * @descript: 登录版本model
 */

namespace App\Models;

class Token extends Model
{
    protected $table    = 'tokens';
    protected $guarded  = ['id', 'created_at', 'updated_at'];
    protected $fillable = ['accountable_type', 'accountable_id', 'type', 'version'];

    /**
     * 增加版本号
     * @param  [type] $id   [description]
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    public static function updateVersion($id, $morph, $type)
    {
        $versions = self::where('accountable_id', $id)
            ->where('accountable_type', $morph)
            ->where('type', $type)
            ->first();

        if ($versions) {
            // 找到加1
            $num = $versions->version + 1;
            $res = $versions->fill(['version' => $num])->save();
            if ($res) {
                return $num;
            } else {
                return 0;
            }
        } else {
            // 没有找到设置1
            $tokens = [
                'accountable_type' => $morph,
                'accountable_id'   => $id,
                'type'             => $type,
                'version'          => 1,
            ];
            $res = self::create($tokens);
            if ($res) {
                return 1;
            } else {
                return 0;
            }
        }
    }
}
